package com.dxj1992.controller.admin.system;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dxj1992.controller.admin.BaseController;
import com.dxj1992.entity.AdminRoles;
import com.dxj1992.entity.AdminUsers;
import com.dxj1992.intercepter.annotation.Access;
import com.dxj1992.service.IAdminRolesService;
import com.dxj1992.service.IAdminUsersService;
import com.dxj1992.utils.ClearCache;
import com.dxj1992.utils.CommonResult;
import com.dxj1992.utils.TableDataInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/admin/system/user")
@Slf4j
public class AdminUsersController extends BaseController {

    @Autowired
    private IAdminUsersService adminUsersService;
    @Autowired
    private IAdminRolesService adminRolesService;
    @Autowired
    private ClearCache clearCache;


    @GetMapping("")
    @Access("system:user:view")
    public String index(HttpServletRequest request, HttpServletResponse response) {
        return "admin/system/user/index";
    }

    @PostMapping("/list")
    @Access("system:user:xxx")
    @ResponseBody
    public TableDataInfo list(Integer pageNum, Integer pageSize, AdminUsers adminUsers) {

        LambdaQueryWrapper<AdminUsers> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(adminUsers.getName())) {
            queryWrapper.like(AdminUsers::getName, adminUsers.getName());
        }

        if (StrUtil.isNotBlank(adminUsers.getName())) {
            queryWrapper.like(AdminUsers::getName, adminUsers.getName());
        }

        if (Objects.nonNull(adminUsers.getStatus())) {
            queryWrapper.eq(AdminUsers::getStatus, adminUsers.getStatus());
        }

        if (StrUtil.isNotBlank((String) adminUsers.getParams().get("beginTime"))) {
            queryWrapper.ge(AdminUsers::getCreatedAt, adminUsers.getParams().get("beginTime") + " 00:00:00");
        }

        if (StrUtil.isNotBlank((String) adminUsers.getParams().get("endTime"))) {
            queryWrapper.le(AdminUsers::getCreatedAt, adminUsers.getParams().get("endTime") + " 23:59:59");
        }

        queryWrapper.orderByDesc(AdminUsers::getId);

        startPage(pageNum, pageSize);
        List<AdminUsers> list = adminUsersService.list(queryWrapper);
        return getDataTable(list);
    }

    @GetMapping("/add")
    public String add() {
        return "admin/system/user/add";
    }

    @PostMapping("/add")
    @ResponseBody
    public CommonResult addSave(AdminUsers adminUsers) {

        adminUsers.setPassword(SecureUtil.md5(adminUsers.getName() + adminUsers.getPassword()));
        boolean save = adminUsersService.save(adminUsers);
        clearCache.clearAdminCache();
        if (!save) {
            CommonResult.failed("添加失败");
        }
        return CommonResult.success("添加成功");
    }

    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public Integer checkLoginNameUnique(@Param("loginName") String loginName) {
        AdminUsers adminUsers = adminUsersService.getOne(Wrappers.<AdminUsers>lambdaQuery().eq(AdminUsers::getName, loginName));
        if (Objects.isNull(adminUsers)) {
            return 0;
        }
        return 1;
    }

    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public Integer checkEmailUnique(@Param("email") String email, @Param("id") String id) {
        AdminUsers adminUsers = adminUsersService.getOne(Wrappers.<AdminUsers>lambdaQuery().eq(AdminUsers::getEmail, email).ne(AdminUsers::getId, id));
        if (Objects.isNull(adminUsers)) {
            return 0;
        }
        return 1;
    }

    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        AdminUsers adminUsers = adminUsersService.getOne(Wrappers.<AdminUsers>lambdaQuery().eq(AdminUsers::getId, id));
        mmap.put("user", adminUsers);
        return "admin/system/user/edit";
    }

    @PostMapping("/edit")
    @ResponseBody
    public CommonResult editSave(AdminUsers adminUsers) {
        boolean save = adminUsersService.updateById(adminUsers);
        clearCache.clearAdminCache();
        if (!save) {
            CommonResult.failed("修改失败");
        }
        return CommonResult.success("修改成功");
    }

    @PostMapping("/remove")
    @ResponseBody
    public CommonResult remove(String ids) {
        String[] split = ids.split(",");
        List<String> strings = Arrays.asList(split);
        boolean b = adminUsersService.removeByIds(strings);
        clearCache.clearAdminCache();
        if (!b) {
            CommonResult.failed("删除失败");
        }
        return CommonResult.success("修改成功");
    }

    @PostMapping("/changeStatus")
    @ResponseBody
    public CommonResult changeStatus(AdminUsers adminUsers) {
        boolean b = adminUsersService.updateById(adminUsers);
        clearCache.clearAdminCache();
        if (!b) {
            return CommonResult.failed("更新失败");
        }
        return CommonResult.success("更新成功");
    }

    @GetMapping("/resetPwd/{id}")
    public String resetPwd(@PathVariable("id") Integer id, ModelMap mmap) {
        AdminUsers adminUsers = adminUsersService.getOne(Wrappers.<AdminUsers>lambdaQuery().eq(AdminUsers::getId, id));
        mmap.put("user", adminUsers);
        return "admin/system/user/resetPwd";
    }

    @PostMapping("/resetPwd")
    @ResponseBody
    public CommonResult resetPwd(AdminUsers adminUsers) {
        adminUsers.setPassword(SecureUtil.md5(adminUsers.getName() + adminUsers.getPassword()));
        boolean b = adminUsersService.updateById(adminUsers);
        if (!b) {
            return CommonResult.failed("更新失败");
        }
        return CommonResult.success("更新成功");
    }

    @GetMapping("/authRole/{id}")
    public String authRole(@PathVariable("id") Integer id, ModelMap mmap) {
        AdminUsers adminUsers = adminUsersService.getOne(Wrappers.<AdminUsers>lambdaQuery().eq(AdminUsers::getId, id));
        List<AdminRoles> adminRoles = adminRolesService.selectRoleById(id);

        mmap.put("user", adminUsers);
        mmap.put("roles", AdminUsers.isAdmin(id) ? adminRoles : adminRoles.stream().filter(r -> !r.isSupAdmin()).collect(Collectors.toList()));
        clearCache.clearAdminCache();
        return "admin/system/user/authRole";
    }

    @PostMapping("/authRole/insertAuthRole")
    @ResponseBody
    @Transactional
    public CommonResult insertAuthRole(AdminUsers adminUsers) {

        boolean b = adminUsersService.insertUserAuth(adminUsers);
        clearCache.clearAdminCache();
        if (!b) {
            return CommonResult.failed("分配失败");
        }
        return CommonResult.success("分配成功");
    }


}
